package com.javer.web.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class LoginFilter implements Filter {
	private static final String USER_NAME = "admin";
	private static final String PASSWORD = "admin";
	private String username;
	private String password;

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		if (request.getSession().getAttribute("login") != null) {
			chain.doFilter(req, resp);			
			return;
		}

		String u = req.getParameter("username");
		String p = req.getParameter("password");
		
		if (username.equals(u) && password.equals(p)) {
			request.getSession().setAttribute("login", username);
			chain.doFilter(req, resp);
			return;
		}
		if (u != null) {
			req.setAttribute("error", "友情提醒：认证失败，请检查！");
		}
		req.getRequestDispatcher("/manage/login.jsp").forward(request, resp);
	}

	public void init(FilterConfig config) throws ServletException {
		username = config.getInitParameter("username") == null ? USER_NAME : config.getInitParameter("username");
		password = config.getInitParameter("password") == null ? PASSWORD : config.getInitParameter("password");
	}

}
